using UnityEngine;
using System.Collections.Generic;
using System;

public class BuildingPlacementManagerUI : MonoBehaviour
{
    [SerializeField] private RectTransform buildingContainer;
    [SerializeField] private RectTransform buildingTemplate;
    [SerializeField] private BuildingTypeListSO buildingTypeListSO;
    Dictionary<BuildingTypeSO,BuildingPlacementManagerUI_Button> buildingButtonDictionary;
    

    private void Awake()
    {
        buildingTemplate.gameObject.SetActive(false);
        buildingButtonDictionary = new Dictionary<BuildingTypeSO, BuildingPlacementManagerUI_Button>();
        foreach (BuildingTypeSO buildingTypeSO in buildingTypeListSO.buildingTypeSOList)
        {
            if (buildingTypeSO.showBuildingPlacement==false)
            {
                continue;
            }
            RectTransform buildingRectTransform = Instantiate(buildingTemplate, buildingContainer);
            buildingRectTransform.gameObject.SetActive(true);
            BuildingPlacementManagerUI_Button buttonSingle
                = buildingRectTransform.GetComponent<BuildingPlacementManagerUI_Button>();
            buildingButtonDictionary[buildingTypeSO] = buttonSingle;
            buttonSingle.Setup(buildingTypeSO);
        }
    }

    private void Start()
    {
        BuildingPlacementManager.Instance.OnActiveBuildingTypeSOChanged += BuildingPlacementManager_OnActiveBuildingTypeSOChanged;
        UpdateSelectedVisual();
    }

    private void BuildingPlacementManager_OnActiveBuildingTypeSOChanged(object sender, EventArgs e)
    {
        UpdateSelectedVisual();
    }

    private void UpdateSelectedVisual()
    {
        foreach (BuildingTypeSO buildingTypeSO in buildingButtonDictionary.Keys)
        {
            buildingButtonDictionary[buildingTypeSO].HideSelected();
        }
        BuildingTypeSO currentBuildingTypeSO = BuildingPlacementManager.Instance.GetActiveBuildingTypeSO();
        buildingButtonDictionary[currentBuildingTypeSO].ShowSelected();
    }
}
